<?php

namespace App\Admin\Controllers;

use App\Admin\Handles\MaterialHandle;
use App\Admin\Selectable\Materials;
use App\Models\PurchaseToMaterial;
use App\Models\RecordMaterial;
use App\Models\Material;
use App\Models\MaterialClassify;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\MessageBag;
use Illuminate\Support\Arr;

class RecordMaterialController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '材料盘点';
    protected $style = [1 => '增加', 2 => '减少'];
    protected $type = [1 => '采购', 2 => '消耗', 3 => '过期', 4 => '盘点'];
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new RecordMaterial());

        $grid->column('material.name', '材料');
        $grid->column('number', '数量');
        $grid->column('description', __('Description'));
        $grid->column('style', '类型')->using([1 => '增加', 2 => '减少']);
        $grid->column('type', '状态')->using($this->type);
        $grid->column('created_at', __('Created at'))->sortable();

        $grid->filter(function ($filter) {
            $filter->disableIdFilter();
             $filter->equal('material.material_classify_id', '分类')
             ->select(Arr::except(MaterialClassify::selectOptions(), '0'));
            $filter->like('material.name', '材料');
            $filter->equal('style', '类型')->radio(Arr::add($this->style, '', '全部'));
            $filter->equal('type', '状态')->radio([
            	1 => '采购', 2 => '消耗', 4 => '盘点', 5 => '退货', '' => '全部'
            ]);
			$filter->between('created_at', '时间')->datetime();
        });
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(RecordMaterial::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('purchase_to_material_id', __('Purchase to material id'));
        $show->field('material_id', __('Material id'));
        $show->field('number', __('Number'));
        $show->field('description', __('Description'));
        $show->field('style', __('Style'));
        $show->field('type', __('Type'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));
        $show->field('deleted_at', __('Deleted at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new RecordMaterial());

        $form->hidden('purchase_to_material_id', __('Purchase to material id'));
        $form->belongsTo('material_id', Materials::class, '材料');
        $form->number('number', '数量')->rules('required|numeric|min:1');
        $form->text('description', __('Description'))->required();

        $form->radioButton('type', '类型')
            ->options([4 => '盘点', 5 => '退货'])
            ->when(4, function (Form $form) {
                $form->select('style', '状态')->options([1 => '增加', 2 => '减少'])
	                ->default('1')
	                ->required();
            })
	        ->when(5, function (Form $form) {
                $form->select('style', '状态')->options([2 => '减少'])
	                ->default('2')
	                ->required();
            })
	        ->required();

        $form->saving(function (Form $form) {
            // 判断是增加还是减少
            if ($form->style == 1) {
                // 查找最新的库存然后增加
                $stock = PurchaseToMaterial::whereHas('purchase',function (Builder $query) {
			            $query->where('status', 2)->where('store_id', 0);
			        })->where('material_id', $form->material_id)
                    ->orderBy('created_at', 'desc')
                    ->first();
                // 判断是否为空
                if(empty($stock)) {
                    $error = new MessageBag([
				        'message' => '没有进货记录无法盘点',
				    ]);
                
                    return back()->with(compact('error'));
                }
                $stock->stock += $form->number;
                $stock->save();
            } elseif($form->style == 2) {
            	// 查找库存总数判断是否够减少
	            $sum = PurchaseToMaterial::whereHas('purchase',function (Builder $query) {
			            $query->where('status', 2)->where('store_id', 0);
			        })->where('material_id', $form->material_id)
                    ->sum('stock');
	            if($sum < $form->number){
	            	$error = new MessageBag([
				        'message' => '库存不足无法减少',
				    ]);
                
                    return back()->with(compact('error'));
	            }
                // 查找库存然后减少
                $stock = PurchaseToMaterial::whereHas('purchase',function (Builder $query) {
			            $query->where('status', 2)->where('store_id', 0);
			        })->where('material_id', $form->material_id)
                    ->where('stock', '>', 0)
                    ->orderBy('created_at', 'asc')
                    ->get();
                // 判断是否为空
	            if(!count($stock)) {
                    $error = new MessageBag([
				        'message' => '没有进货记录无法盘点',
				    ]);
                
                    return back()->with(compact('error'));
                }
	            
                $result = deduction_stock($stock->toArray(), $form->number);
                if(!empty($result)) {
                    foreach ($result as $k => $v){
                        $stock = PurchaseToMaterial::find($v['id']);
                        $stock->sell = $v['sell'];
                        $stock->stock = $v['stock'];
                        $stock->status = $v['status'];
                        $res = $stock->save();
                        //dd($stock->toArray(), $result);
                    }
                }
            }
        });
        return $form;
    }
}
